package com.jiaai.web.zfp.privilege;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSONObject;
import com.jiaai.auth.model.AccessUser;
import com.jiaai.filter.aop.TokenIntercept;
import com.jiaai.member.api.IWalletAPI;
import com.jiaai.privilege.api.IGoodNoApi;
import com.jiaai.util.RequestUtils;
import com.jiaai.util.RestResultGenerator;
import com.jiaai.util.code_pack.ErrorCode;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;

/**
 * class_name:ZBGoodNumController
 * describe:------------------->靓号
 * create_user:张昉平
 * create_date:2018/1/4
 * create_date:17:12
 */
@RestController
@RequestMapping("/api/v1/app/gn")
public class ZGoodNumController {

    @Reference
    private IGoodNoApi iGoodNoApi;
    @Reference
    private IWalletAPI iWalletAPI;

    @GetMapping("/list")
    @TokenIntercept
    public Object list(@RequestParam(required = false, defaultValue = "1") Integer curr){
        return RestResultGenerator.genSuccessResult(iGoodNoApi.getAppList(curr));
    }

    @PostMapping("/buy")
    @TokenIntercept(checkVisitor = true)
    public Object buy(@RequestParam Integer gnId){
        AccessUser user = RequestUtils.getUser();
        try {
            if (iWalletAPI.getMyMoney(user.getUserId()).compareTo(iGoodNoApi.getPrice(gnId)) == -1) {
                return RestResultGenerator.genErrorResult("余额不足,请充值!");
            }

            String s = iGoodNoApi.buy(user.getUserId(), gnId, user.getUserId());
            if (StringUtils.isEmpty(s)){
                return RestResultGenerator.genErrorResult(ErrorCode.GN_BUYED, "靓号已被他人购买了");
            }else if (s.equals("EXIST")){
                return RestResultGenerator.genErrorResult(ErrorCode.GN_EXIST, "本人已拥有靓号");
            }
            return RestResultGenerator.genSuccessResult(JSONObject.parseObject(s));
        } catch (Exception e){
            e.printStackTrace();
            return RestResultGenerator.genErrorResult("服务器异常");
        }
    }

}
